from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request

from info import constants
from info import db
from info.models import Category, News
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu


@profile_blu.route('/base_info', methods=['get', 'post'])
@user_login_data
def base_info():
    user = g.user
    #  如果是get请求直接返回模板
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html',data=data)
    #  如果是post请求代表修改个人信息
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    print(gender)
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    try:
        db.session.commit()
    except Exception as ret:
        db.session.rollback()
        current_app.logger.error(ret)
        return jsonify(errno=RET.DATAERR, errmsg='修改失败')

    return jsonify(errno=RET.OK, errmsg='修改成功')


@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user': user.to_dict()
    }
    print(user.to_dict())
    return render_template('news/user.html', data=data)


@profile_blu.route('/pic_info', methods=['get', 'post'])
@user_login_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_pic_info.html', data=data)

    #  请求方式为post则代表修改头像

    try:
        avatar = request.files.get('avatar').read()
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    key = storage(avatar)

    user.avatar_url = key

    data = {
        'avatar_url': constants.QINIU_DOMIN_PREFIX+key
    }

    return jsonify(errno=RET.OK, errmsg='修改成功', data=data)


@profile_blu.route('/follow',)
@user_login_data
def follow():
    data = {
        'user': g.user.to_dict()
    }
    return render_template('news/user_follow.html', data = data)


@profile_blu.route('/pass_info', methods=['get', 'post'])
@user_login_data
def pass_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='密码错误')

    user.password = new_password

    return jsonify(errno=RET.OK, errmsg='修改成功')


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    user = g.user
    #  获取参数

    page = request.args.get('page', 1)

    try:
        page = int(page)
    except Exception as ret:
        current_app.logger.error(ret)
        page = 1

    #  查询数据
    current_page = 1
    total_page = 1
    news_dict = []
    try:
        paginate = user.collection_news.order_by(News.create_time.desc()).\
            paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_dict = paginate.items
    except Exception as ret:
        current_app.logger.error(ret)

    news_dict = [news.to_basic_dict() for news in news_dict]

    data = {
        'current_page': current_page,
        'total_page': total_page,
        'collections': news_dict
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/news_release',methods=['post', 'get'])
@user_login_data
def news_release():
    user = g.user
    if request.method == 'GET':
        categories = []
        try:
            categories = Category.query.all()
        except Exception as ret:
            current_app.logger.error(ret)

        categories_list = [i.to_dict() for i in categories if i.id != 1]
        data = {
            'categories_list': categories_list
        }
        return render_template('news/user_news_release.html', data=data)

    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    try:
        image_content = index_image.read()
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    try:
        key = storage(image_content)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg='保存图片失败')

    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = user.id
    # 1代表待审核状态
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as ret:
        db.session.rollback()
        current_app.logger.error(ret)
        return jsonify(errno=RET.DATAERR, errmsg='保存失败')

    return jsonify(errno=RET.OK, errmsg='修改成功')


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    user = g.user

    page = request.args.get('page', 1)

    try:
        page = int(page)
    except Exception as ret:
        current_app.logger.error(ret)
        page = 1

    #  查询数据
    current_page = 1
    total_page = 1
    news_dict = []
    try:
        paginate = user.news_list.order_by(News.create_time.desc()).\
            paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_dict = paginate.items
    except Exception as ret:
        current_app.logger.error(ret)

    news_dict = [news.to_review_dict() for news in news_dict]
    data = {
        'current_page': current_page,
        'total_page': total_page,
        'news_list': news_dict
    }
    return render_template('news/user_news_list.html', data=data)

